import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:infinite_scroll_pagination/infinite_scroll_pagination.dart';
import 'package:pornhub_app/components/community_cell/community_cell.dart';
import 'package:pornhub_app/components/no_more/no_data.dart';
import 'package:pornhub_app/components/no_more/no_more.dart';
import 'package:pornhub_app/http/api/api.dart';
import 'package:pornhub_app/model/community/community_model.dart';
import 'package:pornhub_app/utils/color.dart';

class CommunityTabPage extends StatefulWidget {
  final String id;

  const CommunityTabPage({
    super.key,
    required this.id,
  });

  @override
  createState() => _CommunityTabPageState();
}

class _CommunityTabPageState extends State<CommunityTabPage> {
  final PagingController<int, CommunityModel> _pagingControllers =
      PagingController(firstPageKey: 1);
  final EasyRefreshController _refreshController = EasyRefreshController();
  int pageIndex = 1;

  getCommunityDynamicLists({required bool isRefresh}) {
    pageIndex = isRefresh ? 1 : pageIndex++;
    Api.getCommunityDynamicLists(id: widget.id, page: pageIndex)
        .then((response) {
      if (response.isNotEmpty) {
        if (isRefresh) {
          _pagingControllers.refresh();
        }
        _pagingControllers.appendPage(response, pageIndex);
      } else {
        _pagingControllers.appendLastPage([]);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      controller: _refreshController,
      refreshOnStart: true,
      onRefresh: () => getCommunityDynamicLists(isRefresh: true),
      onLoad: () => getCommunityDynamicLists(isRefresh: false),
      child: PagedListView.separated(
        pagingController: _pagingControllers,
        padding: EdgeInsets.only(top: 8.w),
        builderDelegate: PagedChildBuilderDelegate<CommunityModel>(
          firstPageProgressIndicatorBuilder: (context) =>
              const SizedBox.shrink(),
          newPageProgressIndicatorBuilder: (context) => const SizedBox.shrink(),
          noMoreItemsIndicatorBuilder: (context) => const NoMore(),
          noItemsFoundIndicatorBuilder: (context) => const NoData(),
          itemBuilder: (context, item, index) => CommunityCell(model: item),
        ),
        separatorBuilder: (context, index) =>
            Container(height: 5.w, color: COLOR.white.withValues(alpha: 0.3)),
      ),
    );
  }
}
